﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using IS_Ever_Green.DataAccess.Model;
using IS_Ever_Green.DataAccess.Model.Repositories;
using IS_Ever_Green.View;

namespace IS_Ever_Green.ViewModel
{
    public class LoginViewModel : BaseViewModel
    {
        private IUserRepository _userRepository;
        private UserModel _currentUser;
        private ContentControl _recoveryPassword;
        private Visibility _recoveryPasswordVisibility;
        private string _login;
        private string _email;
        private string _password;
        private string _passwordRepeat;

        private string _successfullyMessage;

        private string _errorMessageLogin;
        private string _errorMessageEmail;
        private string _errorMessagePassword;
        private string _errorMessage;

        public UserModel CurrentUser
        {
            get { return _currentUser; }
            set { _currentUser = value; OnPropertyChanged(nameof(CurrentUser)); }
        }

        public ContentControl RecoveryPassword
        {
            get { return _recoveryPassword; }
            set { _recoveryPassword = value; OnPropertyChanged(nameof(RecoveryPassword)); }
        }

        public Visibility RecoveryPasswordVisibility
        {
            get { return _recoveryPasswordVisibility; }
            set { _recoveryPasswordVisibility = value; OnPropertyChanged(nameof(RecoveryPasswordVisibility)); }
        }

        public string Login
        {
            get { return _login; }
            set { _login = value; OnPropertyChanged(nameof(Login)); }
        }

        public string Email
        {
            get { return _email; }
            set
            {
                _email = value;
                OnPropertyChanged(nameof(Email));
            }
        }

        public string Password
        {
            get { return _password; }
            set { _password = value; OnPropertyChanged(nameof(Password)); }
        }

        public string PasswordRepeat
        {
            get { return _passwordRepeat; }
            set
            {
                _passwordRepeat = value;
                OnPropertyChanged(nameof(PasswordRepeat));
            }
        }

        public string SuccessfullyMessage
        {
            get { return _successfullyMessage; }
            set
            {
                _successfullyMessage = value;
                OnPropertyChanged(nameof(SuccessfullyMessage));
            }
        }

        public string ErrorMessageLogin
        {
            get { return _errorMessageLogin; }
            set
            {
                _errorMessageLogin = value;
                OnPropertyChanged(nameof(ErrorMessageLogin));
            }
        }

        public string ErrorMessageEmail
        {
            get { return _errorMessageEmail; }
            set
            {
                _errorMessageEmail = value;
                OnPropertyChanged(nameof(ErrorMessageEmail));
            }
        }

        public string ErrorMessagePassword
        {
            get { return _errorMessagePassword; }
            set
            {
                _errorMessagePassword = value;
                OnPropertyChanged(nameof(ErrorMessagePassword));
            }
        }

        public string ErrorMessage
        {
            get { return _errorMessage; }
            set { _errorMessage = value; OnPropertyChanged(nameof(ErrorMessage)); }
        }

        public ICommand LoginCommand { get; }
        public ICommand OpenModalRecoverPassword { get; }
        public ICommand RecoverPasswordCommand { get; }

        public LoginViewModel()
        {
            _userRepository = new UserRepository();
            LoginCommand = new CommandViewModel(ExecuteLoginCommand, CanExecuteLoginCommand);
            OpenModalRecoverPassword = new CommandViewModel(ExecuteOpenModalRecoverPassword);
            RecoverPasswordCommand = new CommandViewModel(ExecuteRecoverPasswordCommand, CanExecuteRecoverPasswordCommand);
        }

        private bool CanExecuteLoginCommand(object obj)
        {
            return !string.IsNullOrWhiteSpace(Login) && Login.Length >= 3 && !string.IsNullOrWhiteSpace(Password) && Password.Length >= 3;
        }

        private void ExecuteLoginCommand(object obj)
        {

            UserModel user = _userRepository.AuthenticateUser(Login, Password);

            if (user == null)
            {
                ErrorMessage = "Неверный логин или пароль.";
            }
            else
            {
                CurrentUser = user;

                string role = _userRepository.GetUserRole(user);

                if (role == "Admin")
                {
                    OpenAdminView();
                }
                else if (role == "User")
                {
                    OpenUserView();
                }
                else
                {
                    MessageBox.Show("Не удалось определить роль пользователя.");
                }
            }
        }

        private void ExecuteOpenModalRecoverPassword(object obj)
        {
            var recoveryControl = new ModalRecoverPassword();

            RecoveryPassword = recoveryControl;

            RecoveryPasswordVisibility = Visibility.Visible;
        }

        private bool CanExecuteRecoverPasswordCommand(object obj)
        {
            return !string.IsNullOrWhiteSpace(Login) && Login.Length >= 3 &&
                   !string.IsNullOrWhiteSpace(Email) && Email.Length >= 3 &&
                   !string.IsNullOrWhiteSpace(Password) && Password.Length >= 3 &&
                   !string.IsNullOrWhiteSpace(PasswordRepeat) && PasswordRepeat.Length >= 3;
        }

        private void ExecuteRecoverPasswordCommand(object obj)
        {
            ErrorMessageLogin = "";
            ErrorMessageEmail = "";
            ErrorMessagePassword = "";

            ValidateAndSetErrors(Login, Email, Password, PasswordRepeat);

            if (!string.IsNullOrEmpty(ErrorMessageEmail) || !string.IsNullOrEmpty(ErrorMessagePassword) || !string.IsNullOrEmpty(ErrorMessageLogin))
            {
                return;
            }

           

            var user = new UserModel();
            
            user.Password = Password;

            var recoveryPassword = _userRepository.RecoveryPassword(Login,Email, Password);

            if (recoveryPassword == false)
            {
                SuccessfullyMessage = "";
                ErrorMessage = "Не правильный логин или почта";
                return;
            }

            ErrorMessage = "";
            SuccessfullyMessage = "Пароль успешно изменен";
        }

        private void ValidateAndSetErrors(string login, string email, string password, string passwordRepeat)
        {
            if (!_userRepository.UserExists(login))
            {
                ErrorMessageLogin = "Логин не существует";
            }

            if (!email.Contains("@"))
            {
                ErrorMessageEmail = "Некорректный адрес электронной почты.";
            }

            if (password != passwordRepeat)
            {
                ErrorMessagePassword = "Пароли не совпадают";
            }
        }

        private void OpenAdminView()
        {
            var adminView = new AdminView();
            var adminViewModel = adminView.DataContext as AdminViewModel;
            if (adminViewModel != null)
            {
                adminViewModel.CurrentUser = CurrentUser;
            }
            adminView.Show();
            var loginView = Application.Current.Windows.OfType<LoginView>().FirstOrDefault();
            if (loginView != null)
            {
                loginView.Close();
            }
        }

        private void OpenUserView()
        {
            var userView = new UserView();
            var adminViewModel = userView.DataContext as UserViewModel;
            if (adminViewModel != null)
            {
                adminViewModel.CurrentUser = CurrentUser;
            }
            userView.Show();
            var loginView = Application.Current.Windows.OfType<LoginView>().FirstOrDefault();
            if(loginView != null)
            {
                loginView.Close();
            }
        }
    }
}
